package com.akl.ssmspringboot.design_model;



/**
 * 单例模式：懒汉式
 *
 * @Description TODO  第一次调用类时加载实例，存在线程安全问题
 * @Author guoxy
 * @Date 2019/6/25 0025
 * @Version 1.0
 */

public class SingletonLazy {

    private SingletonLazy() {
    }

    private static SingletonLazy single = null;

    /**
     * 静态工厂方法
     * 存在线程安全问题
     *
     * @return
     */
    public static SingletonLazy getInstance() {
        if (single == null) {
            single = new SingletonLazy();
        }
        return single;
    }

    private static SingletonLazy single1;

    /** 解决懒汉模式线程安全的三种方法 */
    /**
     * 1、加锁
     */
    public static synchronized SingletonLazy getInstance1() {
        if (single1 == null) {
            single1 = new SingletonLazy();
        }
        return single1;
    }

    /**
     *  2、双重检查锁（DCL）
     */
    private static volatile SingletonLazy single2;
    public static SingletonLazy getInstance2() {
        if (single2 == null) {
            synchronized (SingletonLazy.class) {
                if (single2 == null) {
                    single2 = new SingletonLazy();
                }
            }
        }
        return single2;
    }

    /**
     *  3、内部类：比上边性能更好，及解决了线程安全问题、又避免了同步带来的性能影响
     */
    private static class LazyHolder {
        private static final SingletonLazy INSTANCE = new SingletonLazy();
    }
    //rivate SingletonLazy (){}       //上边已有
    public static SingletonLazy getInstance3() {
        return LazyHolder.INSTANCE;
    }
}

